package com.glory.dgcpcpda.activity.technicalservice;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.activity.mfg.Eqp_EqpKeepDetailsActivity;
import com.glory.dgcpcpda.adapter.EqpKeepListAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.entity.EqpKeepBean;
import com.glory.dgcpcpda.entity.EqpKeepListBean;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.datepicker.CustomDatePicker;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class Eqp_FixtureMaintenanceActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener {

    boolean isBegin;
    @BindView(R.id.etEqpWork)
    FreeUI_ClearEditText etEqpWork;
    @BindView(R.id.tvEqpWorkDetails)
    TextView tvEqpWorkDetails;
    @BindView(R.id.tvSearch)
    TextView tvSearch;
    @BindView(R.id.rvEqpKeepList)
    RecyclerView rvEqpKeepList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvBeginTime)
    TextView tvBeginTime;
    @BindView(R.id.ivBeginTimeArrow)
    ImageView ivBeginTimeArrow;
    @BindView(R.id.flBeginTimeList)
    FrameLayout flBeginTimeList;
    @BindView(R.id.tvEndTime)
    TextView tvEndTime;
    @BindView(R.id.ivEndTimeArrow)
    ImageView ivEndTimeArrow;
    @BindView(R.id.flEndTimeList)
    FrameLayout flEndTimeList;
    @BindView(R.id.list_tv1)
    TextView listTv1;
    @BindView(R.id.list_tv2)
    TextView listTv2;
    @BindView(R.id.list_tv3)
    TextView listTv3;
    @BindView(R.id.list_tv4)
    TextView listTv4;
    @BindView(R.id.list_tv5)
    TextView listTv5;
    @BindView(R.id.nsScroll)
    NestedScrollView nsScroll;
    @BindView(R.id.cbCreate)
    CheckBox cbCreate;
    @BindView(R.id.cbComplete)
    CheckBox cbComplete;
    @BindView(R.id.cbSave)
    CheckBox cbSave;
    private CustomDatePicker mDatePicker;
    private String beginDate;
    private String endDate;
    private EqpKeepListAdapter eqpKeepListAdapter;
    private List<EqpKeepListBean> xPmsScheduleResults;
    private EqpKeepBean eqpKeepBean;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_eqp_fixture_maintenance;
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        EqpKeepListBean item = eqpKeepListAdapter.getData().get(position);

//        if (!item.getReserved8().equals("已指派")){
//            showToast("当前保养信息未指派",false);
//            return;
//        }

        switch (item.getStatus()) {
            case "CREATE"://创建
            case "WARNING"://警告
            case "CANSTART"://可以开始
            case "TIMEOUT"://超时
                FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "是否开始治具保养?", () -> {

                    FreeUI_EntityCallBack<BaseResponseBean<?>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<?>>
                            (new TypeToken<BaseResponseBean<?>>() {
                            }.getType(), getSupportFragmentManager(), this) {

                        @Override
                        public void onSuccess(Response<BaseResponseBean<?>> response) {
                            super.onSuccess(response);
                            if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                                item.setStatus("START");
                                adapter.notifyItemChanged(position);
                            }
                        }

                        @Override
                        public void onError(Response<BaseResponseBean<?>> response) {
                            super.onError(response);
                            loadError(response.getException(), "PMSSCHEDULE");
                        }
                    };
                    JsonObject map = new JsonObject();
                    map.addProperty("actionType", "startSchedule");
                    map.addProperty("scheduleRrn", item.getScheduleRrn());
                    NetUtils.requestPostNet("CPC.PMSSCHEDULE", "PMSSCHEDULE", this, map, callBack);

                }, () -> {
                }).show(getSupportFragmentManager(), "EQPKEEP");
                break;
            case "START"://已开始
            case "FORM"://已临时保存
                Bundle bundle = new Bundle();
                bundle.putString("scheduleRrn", item.getScheduleRrn());
                bundle.putString("eqpWork", etEqpWork.getText().toString().trim());
                bundle.putString("equipmentDesc", item.getEquipmentDesc());
                bundle.putString("sheetName", item.getSheetName());
                bundle.putInt("jumpType",1);
                FreeApi_Utils.skipWithExtraIntent("header", bundle, Eqp_FixtureMaintenanceActivity.this, Eqp_EqpKeepDetailsActivity.class);
                break;
            case "COMPLETE"://已完成
                showToast("当前保养项已完成", false);
                break;
//            case "TIMEOUT"://超时
//                showToast("当前保养项已超时", false);
//                break;
            default:
                break;
        }
    }

    @Override
    protected void initView() {

        listTv1.setText("保养名称");
        listTv2.setText("保养描述");
        listTv3.setText("状态");
        listTv4.setText("保养时间");
        listTv5.setText("治具");
        listTv1.setVisibility(View.VISIBLE);
        listTv2.setVisibility(View.VISIBLE);
        listTv3.setVisibility(View.VISIBLE);
        listTv4.setVisibility(View.VISIBLE);
        listTv5.setVisibility(View.VISIBLE);
        initDatePicker();
        initEdit(etEqpWork, s -> {
        });
        beginDate = FreeApi_DateUtils.getAfterStringDate(new Date(System.currentTimeMillis()), "yyyy-MM-dd", -3);
        tvBeginTime.setText(beginDate);
        endDate = FreeApi_DateUtils.getAfterStringDate(new Date(System.currentTimeMillis()), "yyyy-MM-dd", 7);
        tvEndTime.setText(endDate);

        rvEqpKeepList.setLayoutManager(new LinearLayoutManager(Eqp_FixtureMaintenanceActivity.this));
        rvEqpKeepList.setItemAnimator(new DefaultItemAnimator());
        rvEqpKeepList.addItemDecoration(new DividerItemDecoration(Eqp_FixtureMaintenanceActivity.this, 1));
        eqpKeepListAdapter = new EqpKeepListAdapter(null);
        eqpKeepListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        eqpKeepListAdapter.isFirstOnly(true);
        rvEqpKeepList.setAdapter(eqpKeepListAdapter);

        eqpKeepListAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void initData() {

    }

    private void initDatePicker() {
        long beginTimestamp = FreeApi_DateUtils.str2Long("1992-03-20", false);
        long endTimestamp = FreeApi_DateUtils.str2Long("2222-02-22", false);

        // 通过时间戳初始化日期，毫秒级别
        mDatePicker = new CustomDatePicker(this, timestamp -> {
            if (isBegin) {
                beginDate = FreeApi_DateUtils.long2Str(timestamp, false);
                tvBeginTime.setText(beginDate);
            } else {
                endDate = FreeApi_DateUtils.long2Str(timestamp, false);
                tvEndTime.setText(endDate);
            }

        }, beginTimestamp, endTimestamp);
        // 不允许点击屏幕或物理返回键关闭
        mDatePicker.setCancelable(true);
        // 不显示时和分
        mDatePicker.setCanShowPreciseTime(false);
        // 不允许循环滚动
        mDatePicker.setScrollLoop(false);
        // 不允许滚动动画
        mDatePicker.setCanShowAnim(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (etEqpWork.getText().toString().trim().length() == 0) {
            return;
        }
        search();
    }

    @OnClick({R.id.flBeginTimeList, R.id.flEndTimeList, R.id.tvSearch})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flBeginTimeList:
                isBegin = true;
                mDatePicker.show(System.currentTimeMillis());
                break;
            case R.id.flEndTimeList:
                isBegin = false;
                mDatePicker.show(System.currentTimeMillis());
                break;
            case R.id.tvSearch:

                if (etEqpWork.getText().toString().trim().length() == 0) {
                    showToast("治具号不能为空", false);
                    return;
                }
                if (!FreeApi_StringUtils.isEmpty(beginDate) && !FreeApi_StringUtils.isEmpty(endDate)) {
                    int i = FreeApi_DateUtils.compare_date(endDate, beginDate, "yyyy-MM-dd");
                    if (i != 1) {
                        showToast("结束日期不能大于开始日期", false);
                        tvBeginTime.setText("请选择开始日期");
                        tvEndTime.setText("请选择结束日期");
                        beginDate = "";
                        endDate = "";
                        return;
                    }
                    search();
                } else {
                    showToast("开始时间和结束时间不能为空", false);
                }

                break;
        }
    }

    private void search() {

        FreeUI_EntityCallBack<BaseResponseBean<EqpKeepBean>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EqpKeepBean>>
                (new TypeToken<BaseResponseBean<EqpKeepBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EqpKeepBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    eqpKeepBean = response.body().getResponse().getBody();
                    tvEqpWorkDetails.setText(eqpKeepBean.getEqpDesc());
                    xPmsScheduleResults = eqpKeepBean.getXPmsScheduleResults();
                    List<EqpKeepListBean> checkData = new ArrayList<>();
                    checkData.clear();
                    if (xPmsScheduleResults.size() > 0) {
                        if (!cbComplete.isChecked() & !cbCreate.isChecked() & !cbSave.isChecked()) {
                            List<EqpKeepListBean> dataList = new ArrayList<>();
                            for (EqpKeepListBean data : xPmsScheduleResults) {
                                if (!data.getStatus().equals("CANCEL")){
                                    dataList.add(data);
                                }
                            }
                            eqpKeepListAdapter.setNewData(getCollections(dataList));

                        } else {
                            for (EqpKeepListBean data : xPmsScheduleResults) {
                                String status = data.getStatus();
                                if (!status.equals("CANCEL")){
                                    if (cbCreate.isChecked()) {
                                        if (status.equals("TIMEOUT") | status.equals("CREATE") | status.equals("WARNING")
                                                | status.equals("CANSTART") | status.equals("START")) {
                                            checkData.add(data);
                                        }
                                    }

                                    if (cbComplete.isChecked()) {
                                        if (status.equals("COMPLETE")) {
                                            checkData.add(data);
                                        }
                                    }

                                    if (cbSave.isChecked()) {
                                        if (status.equals("FORM")) {
                                            checkData.add(data);
                                        }
                                    }
                                }
                            }

                            if (checkData.size() <= 0) {
                                showConfirmDialog("当前状态下无保养计划");
                                eqpKeepListAdapter.setNewData(null);
                            } else {
                                eqpKeepListAdapter.setNewData(getCollections(checkData));
                            }
                        }
                    } else {
                        showConfirmDialog("暂无保养计划");
                        eqpKeepListAdapter.setNewData(null);
                    }

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<EqpKeepBean>> response) {
                super.onError(response);
                loadError(response.getException(), "PMSSCHEDULE");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("actionType", "query");
        map.addProperty("eqpId", etEqpWork.getText().toString().trim());
        map.addProperty("startTime", beginDate);
        map.addProperty("endTime", endDate);
        NetUtils.requestPostNet("CPC.PMSSCHEDULE", "PMSSCHEDULE", this, map, callBack);

    }

    private List<EqpKeepListBean> getCollections(List<EqpKeepListBean> dataList) {
        Collections.sort(dataList, new Comparator<EqpKeepListBean>() {
            @Override
            public int compare(EqpKeepListBean o1, EqpKeepListBean o2) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                try {
                    Date dt1 = format.parse(o1.getScheduleDate());
                    Date dt2 = format.parse(o2.getScheduleDate());
                    if (dt1.getTime() > dt2.getTime()) {
                        return 1;
                    } else if (dt1.getTime() < dt2.getTime()) {
                        return -1;
                    } else {
                        return 0;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
        return dataList;
    }


    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("治具保养");
        return new FreeUI_AddViewEntity("header", llMain);
    }
}